﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;

namespace PADWH35
{
    public partial class MaterialRequisition : Form
    {
        DataTable dt = new DataTable();
        int time = 0;
        int index = 1;
        // <summary>
        /// 窗体改变前的Width宽度
        /// </summary>
        private int iForm_ResizeBefore_Width;

        /// <summary>
        /// 窗体改变前的Height高度
        /// </summary>
        private int iForm_ResizeBefore_Height;

        /// <summary>
        /// 取得Form中控件中初始的字体大小，即无论Form多大此字体都是Form中最小值
        /// </summary>
        private Dictionary<Control, float> FontSizeMin = new Dictionary<Control, float>();

        /// <summary>
        /// 宽比例，float类型，此处为每次改后窗体的宽度 除以改变前窗体的宽度的比例
        /// </summary>
        private float fRatio_Width;

        /// <summary>
        /// 高比例，float类型，此处为每次改后窗体的高度 除以改变前窗体的高度的比例
        /// </summary>
        private float fRatio_Height;
        string load = "加载中";
        /// <summary>
        /// 存储物料明细
        /// </summary>
        private Dictionary<string, DataTable> DetailPart = new Dictionary<string, DataTable>();
        public MaterialRequisition()
        {

            InitializeComponent();
            try
            {
                this.WindowState = FormWindowState.Maximized;
                //设置最小大小为窗体打开的初始大小
                this.MinimumSize = this.Size;
                FontSizeMin = new Dictionary<Control, float>();
                //取得Form中控件中初始的字体大小 //若此From中字体不统一，则此处为数组。
                getlist(this);
                //FontSizeMin = this.label1.Font.Size;
                //获得窗体改变前的Form的宽度与高度 //赋初始值
                iForm_ResizeBefore_Width = this.Size.Width;
                iForm_ResizeBefore_Height = this.Size.Height;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }

        /// <summary>
        /// 获取控件字体大小值
        /// </summary>
        /// <param name="controls"></param>ss
        private void getlist(Control controls)
        {
            try
            {
                foreach (Control OneCon in controls.Controls)
                {
                    FontSizeMin.Add(OneCon, OneCon.Font.Size);
                    if (OneCon.Controls.Count > 0)
                    {
                        getlist(OneCon);// 如Form内还有控件中的控件，此处则可递归改变大小，此处为重点中的重点 

                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }

        // <summary>
        /// 自适应窗体大小的方法，递归
                /// </summary>
                /// <param name="theControl"></param>
        private void AutoResize(Control theControl)  //核心代码
        {
            try
            {
                #region 控制控件自适应UI大小
                foreach (Control OneCon in theControl.Controls)   //根据原大小等比例放大
                {
                    OneCon.Left = Convert.ToInt32((OneCon.Left * fRatio_Width));
                    OneCon.Top = Convert.ToInt32((OneCon.Top * fRatio_Height));
                    OneCon.Width = Convert.ToInt32(OneCon.Width * fRatio_Width);
                    OneCon.Height = Convert.ToInt32(OneCon.Height * fRatio_Height);
                    if (OneCon.Controls.Count > 0)
                    {
                        AutoResize(OneCon);//如Form内还有控件中的控件，此处则可递归改变大小，此处为重点中的重点  
                    }
                    #region 自动更改字体的大小  //2020-03-23 19:21:50 更新
                    // 当前控件（OneCon.Font.Size） 乘以(8)  长宽比例中最小值 (Math.Min(fRatio_Width, fRatio_Height)
                    //Math.Round(数值, 2) //保留两位有效数字
                    float currentSize = float.Parse(Math.Round(OneCon.Font.Size * (Math.Min(fRatio_Width, fRatio_Height)), 2).ToString());
                    if (currentSize > FontSizeMin[OneCon])
                        OneCon.Font = new Font(OneCon.Font.Name, currentSize, OneCon.Font.Style, OneCon.Font.Unit);
                    else
                        OneCon.Font = new Font(OneCon.Font.Name, FontSizeMin[OneCon], OneCon.Font.Style, OneCon.Font.Unit);
                    //某种程度上来说 if 语句都可以改成三目运算符， 举例： m=a>b?a:b; 表示先判断a是否大于b，若a>b,则将a的值赋给m，若不符合a>b,则将b的值赋给m
                    //float NowSize = currentSize > FontSizeMin ? currentSize : FontSizeMin;
                    //OneCon.Font = new Font(OneCon.Font.Name, NowSize, OneCon.Font.Style, OneCon.Font.Unit);
                    #endregion
                }
                #endregion
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //窗体改变后Form的宽度与高度及宽比例和高比例
            try
            {
                fRatio_Width = (this.Size.Width / (float)iForm_ResizeBefore_Width);
                fRatio_Height = (this.Size.Height / (float)iForm_ResizeBefore_Height);
                AutoResize(this);
                ////获得下一次窗体改变前的Form的宽度与高度

                iForm_ResizeBefore_Width = this.Size.Width;
                iForm_ResizeBefore_Height = this.Size.Height;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                timer2.Start();
                //dataGridView1.DataSource = dt;         
                backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }

        }

        private void timerTime_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void refreashData(int index, DataTable data)
        {
            try
            {
                if (data.Rows.Count > 0 && DetailPart.ContainsKey(data.Rows[index]["领料单"].ToString()) && DetailPart[data.Rows[index]["领料单"].ToString()].Rows.Count > 0)
                {

                    lbCompany.Text = data.Rows[index]["公司"].ToString();
                    lbDate.Text = data.Rows[index]["单据日期"].ToString().Substring(0, 10);
                    lbDept.Text = data.Rows[index]["部门"].ToString();
                    lbIssueNo.Text = data.Rows[index]["领料单"].ToString();
                    lbPerson.Text = data.Rows[index]["制单人"].ToString();
                    lbType.Text = data.Rows[index]["领料类型"].ToString();
                    dataGridView1.DataSource = DetailPart[data.Rows[index]["领料单"].ToString()];
                    if (dataGridView1.RowCount > 0)
                    {
                        dataGridView1.ClearSelection();
                        dataGridView1.Columns["物料"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        //dataGridView1.Columns["物料"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                        dataGridView1.Columns["需求日期"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["领料单号"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["成品 / 半成品"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["工单数量"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["申请数量"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["库存数"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["工单"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["单位"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["是否有交易"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
                        dataGridView1.Columns["发料数量"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        dataGridView1.Columns["物料序号"].Visible = false;
                        dataGridView1.Columns["领料单号"].Visible = false;
                        dataGridView1.Columns["半成品序号"].Visible = false;
                    }
                    //库存数小于申请数红色显示
                    for (int k = 0; k < dataGridView1.Rows.Count; k++)
                    {
                        string quantityInStaock = dataGridView1.Rows[k].Cells["库存数"].Value.ToString();
                        string applyNum = dataGridView1.Rows[k].Cells["申请数量"].Value.ToString();
                        string deliverNum = dataGridView1.Rows[k].Cells["发料数量"].Value.ToString();

                        if (!string.IsNullOrEmpty(quantityInStaock) && !string.IsNullOrEmpty(applyNum))
                        {
                            if (Convert.ToDouble(quantityInStaock) < Convert.ToDouble(applyNum))
                            {
                                dataGridView1.Rows[k].DefaultCellStyle.ForeColor = Color.Red;
                            }
                        }

                        //if (!string.IsNullOrEmpty(deliverNum) && !string.IsNullOrEmpty(applyNum))
                        //{
                        //    if (Convert.ToDouble(deliverNum) >= Convert.ToDouble(applyNum))
                        //    {
                        //        DataGridViewRow row = dataGridView1.Rows[k];
                        //        dataGridView1.Rows.Remove(row);
                        //    }
                        //}
                        //if(dataGridView1.Rows.Count<=0)
                        //{
                        //    this.index++;
                        //    refreashData(this.index, dt);
                        //}
                    }
                }
                else
                {
                    lbCompany.Text = "";
                    lbDate.Text = "";
                    lbDept.Text = "";
                    lbIssueNo.Text = "";
                    lbPerson.Text = "";
                    lbType.Text = "";
                    dataGridView1.DataSource = null;
                    addIndex();
                    refreashData(this.index, dt);
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                progressBar1.Value = time * 10;
                if (time == 10)
                {
                    refreashData(index, dt);
                    addIndex();
                    time = 0;
                }
                time++;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }
        private void addIndex()
        {
            try
            {
                if (index < dt.Rows.Count - 1)
                {
                    index++;
                }
                else
                {
                    index = 0;
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                dt = getData.getHeadData();
                DetailPart = getData.getDetail(dt);
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (dt.Rows.Count > 0 && DetailPart.Count > 0)
                {
                    refreashData(0, dt);
                    //数据刷新出来后绑定鼠标进出datagridview的事件
                    this.dataGridView1.MouseEnter += new System.EventHandler(this.dataGridView1_MouseEnter);
                    this.dataGridView1.MouseLeave += new System.EventHandler(this.dataGridView1_MouseLeave);
                    timer1.Start();
                    timer2.Stop();
                }
                else
                {
                    timer2.Stop();
                    lbCompany.Text = "暂无数据";
                    lbDate.Text = "暂无数据";
                    lbDept.Text = GetConfig("dept_");
                    lbIssueNo.Text = "暂无数据";
                    lbPerson.Text = "暂无数据";
                    lbType.Text = "暂无数据";
                }
            }
            catch (Exception ex)
            {
                WriteLog.Writelog(ex.ToString());
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            lbCompany.Text = load;
            lbDate.Text = load;
            lbDept.Text = load;
            lbIssueNo.Text = load;
            lbPerson.Text = load;
            lbType.Text = load;
            load += "。";
            if (load == "加载中。。。。")
            {
                load = "加载中";
            }
        }

        private void dataGridView1_MouseEnter(object sender, EventArgs e) => timer1.Stop();

        private void dataGridView1_MouseLeave(object sender, EventArgs e) => timer1.Start();

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) => System.Environment.Exit(0);

        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConfig(string name)
        {
            try
            {
                string value = null;
                XmlDocument doc = new XmlDocument();
                //获得配置文件的全路径  
                string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;//AppDomain.CurrentDomain.BaseDirectory.ToString() + ".exe.config";
                doc.Load(strFileName);
                //找出名称为“add”的所有元素  
                XmlNodeList nodes = doc.GetElementsByTagName("add");
                for (int i = 0; i < nodes.Count; i++)
                {
                    //获得将当前元素的key属性  
                    XmlAttribute att = nodes[i].Attributes["name"];
                    //根据元素的第一个属性来判断当前的元素是不是目标元素  
                    if (att.Value == name)
                    {
                        //对目标元素中的第二个属性赋值  
                        att = nodes[i].Attributes["connectionString"];
                        value = att.Value;
                        break;
                    }
                }
                //保存上面的修改  
                return value;
            }
            catch (Exception ex) { WriteLog.Writelog(ex.ToString()); return ""; }

        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }
    }
}
